define(['common/js/filter/boss-filter-0.1','common/lib/emailtip/jquery.emailtip.js'],function() {
    var gridFormTip = {
        default: {
            "required": "该字段不能为空",
            "minlength": "该字段长度不能小于{{minlength}}",
            "maxlength": "该字段长度不能大于{{maxlength}}",
            "pattern": "您输入的格式有误"
        }
    };

    diretiveModule.directive('plusDataGrid', function ($injector) {
        var formName = "plusDynamicForm";
        for (var i = 0; i < 6; i++) {
            formName += Math.ceil(Math.random() * 10);
        }

        return {
            scope: false,
            restrict: "E",
            replace: true,
            transclude: true,
            controller: function ($scope) {
                //表单属性
                $scope.formNames = [];
                $scope.formValidation = {};
                $scope.defaultValidation = {};
                $scope.validStrs = ["required", "minlength", "maxlength", "pattern"];

                $scope.myData = [];
                $scope.cleanNames = [];//使用“Form setPristine”清空的条件项
                $scope.refreshNames = [];//使用“广播”清空的条件项
                $scope.searchNames = [];//用户作为搜索条件
                $scope.searchConditions = {};
                $scope.originalSearchConditions = {};//包含整个对象的搜索条件（{select-key:xx,select-value:xx}）

                $scope.selectedIndexes = [];

                $scope.searchOnLoadEcho = {};

                var page = 1;
                var pageSize = 10;
                $scope.searchConditions = {
                    page: page,
                    pageSize: pageSize
                };
                $scope.lastSearchConditions = {};
                //是否发出过搜索请求
                $scope.hasSearched = false;
                //是否正在搜索
                $scope.isSearching = false;
                // 是否允许操作
                $scope.operateAllowed = false;

                // 分页相关数据
                $scope.pagingOptions = {
                    myData: [],

                    pageSizes: [10, 20, 30],
                    currentPage: page,
                    pageSize: pageSize,

                    totalPage: null,
                    totalResults: null,
                    pageIndexes: []
                };
                //其他请求信息
                $scope.otherInfo = {};


                $scope.searchGrid = function (specCondition) {
                    $scope.searchOnLoadEcho = angular.extend({}, $scope.searchOnLoadEcho, specCondition);

                    if ($scope.isSearching) {
                        return;
                    }
                    $scope.isSearching = true;

                    $scope.gridErrorMsg = "";

                    //表单验证
                    for (var index in $scope.formNames) {
                        var name = $scope.formNames[index];
                        var nameObj = $scope[formName][name];
                        var nameValidation = $scope.defaultValidation[name];
                        for (var key in nameValidation) {
                            if (nameObj.$error[key]) {
                                $scope.gridErrorMsg = nameValidation[key];
                                $scope.isSearching = false;
                                return;
                            }
                        }
                    }
                    // 验证通过

                    $scope.hasSearched = true;//已请求

                    //记录搜索条件
                    console.log($scope.searchConditions);
                    var lastCondition = angular.copy($scope.searchConditions);

                    //判断是否由使用者
                    if($scope.searchOnLoadEcho){
                        if(!lastCondition.page){
                            lastCondition.page = $scope.searchConditions.page;
                            lastCondition.pageSize = $scope.searchConditions.pageSize;
                        }
                    }

                    //去除空字符串的值
                    for (var key in lastCondition) {
                        if (lastCondition[key] === "") {
                            delete lastCondition[key];
                        }
                    }

                    $scope.lastSearchConditions = lastCondition;

                    lastCondition = angular.extend({}, $scope.searchOnLoadEcho,lastCondition);
                    $scope.requestGridData(lastCondition).then(function (pager) {
                        console.log("请求成功 === = ==");
                        console.log(pager);

                        if($scope.selectable){
                            //反选
                            emptySelectedIndexes();
                        }

                        $scope.operateAllowed = pager.totalResults > 0 ? true : false; //是否允许操作

                        $scope.pagingOptions.myData = pager.data;
                        $scope.pagingOptions.totalResults = pager.totalResults;
                        $scope.pagingOptions.totalPage = pager.totalPage;
                        $scope.pagingOptions.currentPage = pager.currentPage;
                        $scope.pagingOptions.pageSize = pager.onePageSize;

                        var showNum = 9;//最多显示分页数
                        var halfNum = Math.floor(showNum / 2);
                        var totalPage = pager.totalPage;
                        var startIndex = 1, endIndex = totalPage;
                        var currentPage = pager.currentPage;

                        if (pager.totalPage > showNum) {
                            if (currentPage < (1 + halfNum)) {
                                startIndex = 1;
                                endIndex = showNum;
                            } else if (currentPage > (totalPage - halfNum)) {
                                startIndex = totalPage - showNum + 1;
                                endIndex = totalPage;
                            } else {
                                startIndex = currentPage - halfNum;
                                endIndex = currentPage + halfNum;
                            }
                        }

                        $scope.pagingOptions.pageIndexes.length = 0;//清空数组
                        for (var i = startIndex; i <= endIndex; i++) {
                            $scope.pagingOptions.pageIndexes.push(i);
                        }

                        //搜索数据返回之后的回调
                        if($scope.searchAfterGrid){
                            $scope[$scope.searchAfterGrid]($scope.pagingOptions);
                        }

                        $scope.isSearching = false;
                    },function(error){
                        $scope.isSearching = false;
                    });

                    //请求其他附带数据
                    if ($scope.requestOtherData) {
                        $scope.requestOtherData(lastCondition).then(function (obj) {
                            $scope.otherInfo = obj;

                            //搜索数据返回之后的回调
                            if($scope.searchAfterOther){
                                $scope[$scope.searchAfterOther](obj);
                            }
                        });
                    }
                };

                //添加事件监听
                $scope.$on("reloadGrid", function (event,condition) {
                    $scope.searchGrid(condition);
                });

                //条件发生变更
                $scope.$watch("searchConditions", function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        $scope.operateAllowed = false;
                    }
                }, true);

                $scope.emptySearchConditions = emptySearchConditions;

                function emptySearchConditions(){
                    $scope.errorMsg = "";

                    //变量清空了面没反应bug修复
                    setTimeout(function() {
                        $scope.$apply(function() {
                            delete $scope.searchOnLoadEcho;
                            // 通过表单处理清空
                            for(var key in $scope.cleanNames){
                                var name = $scope.cleanNames[key];
                                $scope.searchConditions[name] = "";
                                if($scope[formName][name]){
                                    $scope[formName][name].$setPristine();
                                }
                            }

                            //通过事件广播清空
                            for(var index2 in $scope.refreshNames){
                                $scope.$broadcast("refresh-"+$scope.refreshNames[index2]);
                            }
                        });
                    }, 100);
                }

                //清空选中的想
                function emptySelectedIndexes(){
                    $scope.selectedIndexes.length = 0;
                    var i,len;
                    if(!!$scope.pagingOptions.myData){
                        for(i = 0,len = $scope.pagingOptions.myData.length;i<len;i++){
                            $scope.selectedIndexes[i] = false;
                        }
                    }
                }

            },
            template: '<form novalidate class="form-inline" role="form" name="' + formName + '">' +
            '<div ng-show="gridErrorMsg" class="form-group" style="padding-left:35px;padding-bottom:10px;"><span class="text-lg text-danger">{{gridErrorMsg}}</span></div>' +
            '<div ng-transclude></div>' +
            '</form>',
            compile: function (tElm, tAttrs) {
                return {
                    pre: function (scope, elm, attrs) {
                        if (!attrs.serviceName) {
                            console.error("plusDataGrid的属性service-name不能为空");
                            return;
                        }
                        if (!attrs.serviceMethod) {
                            console.error("plusDataGrid的属性service-method不能为空");
                            return;
                        }

                        //初始化条件
                        if(attrs.initialCondition){
                            if(!scope[attrs.initialCondition]){
                                console.error("plusDataGrid的属性initial-condition值在$scope里面找不到");
                                return;
                            }

                            scope.hasInitial = true;

                            var initialCon = scope[attrs.initialCondition];
                            for(var key in initialCon){
                                scope.searchConditions[key]  = initialCon[key];
                            }
                        }

                        scope.requestGridData = $injector.get(attrs.serviceName)[attrs.serviceMethod];

                        if (attrs.otherServiceName && attrs.otherServiceMethod) {
                            scope.requestOtherData = $injector.get(attrs.otherServiceName)[attrs.otherServiceMethod];
                        }

                        //自定义验证信息
                        if (attrs.formValidation) {
                            scope.formValidation = scope[attrs.formValidation];
                        }

                        //是否指令加载时就启动数据
                        var tmpVar = true;
                        if (attrs.searchOnLoad && attrs.searchOnLoad == "false") {
                            tmpVar = false;
                        }
                        scope.searchOnLoad = tmpVar;

                        //搜索无结果后的提示
                        scope.searchTipBefore = attrs.searchTipBefore ? attrs.searchTipBefore : "请先搜索你要操作的选项";
                        scope.searchTipNone = attrs.searchTipNone ? attrs.searchTipNone : "搜索内容为空，请变更搜索条件";

                        scope.searchAfterGrid = attrs.searchAfterGrid;
                        scope.searchAfterOther = attrs.searchAfterOther;

                        //添加表单回显监听
                        if(attrs.echo){
                            scope.echo = true;

                            scope.$on("echoGrid-"+attrs.gridName,function(event,echoValue){
                                if(!angular.isObject(echoValue)){
                                    console.error("回显数据格式有误，必须是json格式,key为searh-bar中的'搜索'字段");
                                    return;
                                }

                                //更改搜索条件数据
                                for(var ii in scope.searchNames){
                                    var echoV = echoValue[scope.searchNames[ii]];
                                    if(echoV != undefined){
                                        scope.searchConditions[scope.searchNames[ii]] = echoV;
                                    }
                                }

                                //更改显示
                                //通过事件广播更改（无法通过双向绑定更改）
                                for(var index2 in scope.refreshNames){
                                    var echoConditionName = scope.refreshNames[index2];
                                    if(echoValue[echoConditionName]){
                                        scope.$broadcast("echo-"+echoConditionName,echoValue[echoConditionName]);
                                    }
                                }
                            });
                        }

                        // 选择广播
                        if(attrs.selectable && attrs.selectable == 'true'){
                            scope.selectable = true;
                            scope.$on("selectItem-"+attrs.gridName,function(event,echoIndexes){
                                if(!angular.isArray(echoIndexes) && echoIndexes!=1 && echoIndexes!=-1){
                                    console.error("选择行数参数有误，-1,1或数组");
                                    return;
                                }

                                /*            for(var i in scope.selectedIndexes){
                                 scope.selectedIndexes[i] = false;
                                 }*/

                                //选中
                                if(echoIndexes == 1){
                                    var i,len = scope.pagingOptions.myData.length;
                                    for(i=0;i<len;i++){
                                        scope.selectedIndexes[i] = true;
                                    }
                                } else if(echoIndexes == -1) {
                                    var j, myDataLen = scope.pagingOptions.myData.length;

                                    for(j =0; j<myDataLen; j++) {

                                        scope.selectedIndexes[j] = scope.selectedIndexes[j] ? false : true;
                                    }

                                } else {
                                    for(var i in echoIndexes){
                                        /*    scope.selectedIndexes[echoIndexes[i]] = true;*/
                                        scope.selectedIndexes[echoIndexes[i]] = scope.selectedIndexes[echoIndexes[i]] ? false : true;
                                    }
                                }

                                scope.selectChangeH();
                            });

                            // 列表选择操作
                            scope.selectChangeH = function(){
                                //回调
                                if(!attrs.onSelectChange || typeof scope[attrs.onSelectChange]!='function'){
                                    return;
                                }

                                var i,
                                    indexes = scope.selectedIndexes,
                                    objs = scope.pagingOptions.myData,
                                    sObjs = [];
                                for(i in indexes){
                                    if(indexes[i]){
                                        sObjs.push(objs[i]);
                                    }
                                }
                                scope[attrs.onSelectChange](sObjs);
                            };

                            scope.$watch("selectedIndexes", function (newVal, oldVal) {
                                //if (newVal && newVal.length !== oldVal.length) {
                                scope.selectChangeH();
                                //}
                            },true);
                        }

                    }
                };
            }
        };
    });

    diretiveModule.directive('gridToolBar', function () {
        return {
            scope: false,
            restrict: "E",
            replace: true,
            require: '^plusDataGrid',
            transclude: true,
            controller: function ($scope) {
            },
            template: function (tElm, tAttrs) {
                var visible = true;
                if (!tAttrs || tAttrs.barVisible != "true") {
                    visible = true;
                }
                var val = visible ? "show" : "hidden";
                return '<div class="form-group pull-right ' + val + '" ng-transclude></div>';
            }
        };
    });

    diretiveModule.directive('toolAdd', function () {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridToolBar',
            controller: function ($scope) {
            },
            template: function (tElm, tAttrs) {
                var toolLabel = tAttrs.toolLabel ? tAttrs.toolLabel : "新&nbsp;&nbsp;&nbsp;增";
                return '<a id="toolAddHref" class="btn btn-primary from-control" style="width:172px;" ng-click="addDoIt()">' + toolLabel + '</a>';
            },
            link: function (scope, elm, attrs) {
                scope.addDoStr = attrs.addDo;

                scope.addDoIt = function () {
                    console.log("= = = = =  =add-do == 调用");
                    if (scope.addDoStr) {
                        scope[scope.addDoStr]();
                    }
                };
            }
        };
    });

    diretiveModule.directive('toolBack', function () {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridToolBar',
            controller: function ($scope, $location) {
                $scope.backDoIt = function () {
                    $location.path($scope.toolConf.backRoute);
                }
            },
            template: '<a class="btn btn-primary from-control" style="width:172px;" ng-click="backDoIt()">{{toolConf.toolLabel}}</a>',
            link: function (scope, elm, attrs) {
                scope.backDoStr = attrs.backDo;
                scope.toolConf = {
                    backRoute: attrs.backRoute,
                    toolLabel: attrs.toolLabel ? attrs.toolLabel : "返&nbsp;&nbsp;&nbsp;回"
                };
            }
        };
    });

    diretiveModule.directive('gridSearchBar', function () {
        return {
            scope: false,
            restrict: "E",
            replace: true,
            require: '^plusDataGrid',
            transclude: true,
            controller: function ($scope, $injector) {
                $scope.barSearch = function () {
                    if ($scope.searchDo) {
                        for(var key in $scope.searchConditions){
                            if(!angular.isObject($scope.originalSearchConditions[key])){
                                $scope.originalSearchConditions[key] = $scope.searchConditions[key];
                            }
                        }

                        var result = $scope.searchDo($scope.searchConditions,$scope.originalSearchConditions);
                        if (!result) {
                            return;
                        }
                    }

                    $scope.searchGrid();
                };
                $scope.resetSearchInput = function(){
                    $scope.emptySearchConditions();
                };
            },
            template: function (tElm, tAttrs) {
                var visible = false;
                if (!tAttrs || tAttrs.barVisible != "false") {
                    visible = true;
                }

                var showClass = visible ? "" : "style='display:none;'";

                var tmpStr =  '<div class="form-group grid-search-bar" '+showClass+'>' +
                    '<temp ng-transclude></temp>' +
                    '<button type="submit" class="btn btn-primary mr10" ng-click="barSearch()">搜 索</button>';
                if(!tAttrs.reset || tAttrs.reset!="false"){
                    tmpStr += '<button type="submit" class="btn btn-default" ng-click="emptySearchConditions()">清 空</button>';
                }
                tmpStr += '</div>';

                return tmpStr;
            },
            link: function (scope, elm, attrs) {
                if (attrs.searchDo) {
                    scope.searchDo = scope[attrs.searchDo];
                }
            }
        };
    });

    diretiveModule.directive('gridConditionHide', function () {
        return {
            scope: true,
            restrict: "E",
            replace: false,
            require: '^gridSearchBar',
            link: function (scope, elm, attrs, searchBarCtrl) {
                scope.searchNames.push(attrs.conditionName);
                scope.searchConditions[attrs.conditionName] = attrs.conditionValue;
                var broadcast = attrs.broadcast && attrs.broadcast == "true";
                if (broadcast) {
                    scope.$on("reload-" + attrs.conditionName, function (event, conditionObj) {
                        scope.searchConditions[attrs.conditionName] = conditionObj;
                    });
                }
            }
        };
    });

    diretiveModule.directive('gridConditionText', function () {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridSearchBar',
            template: function (tElm, tAttrs) {
                var conditionName = "searchConditions." + tAttrs.conditionName;
                var conditionType = tAttrs.conditionType ? tAttrs.conditionType : "text";
                var conditionTip = tAttrs.conditionTip ? tAttrs.conditionTip : "";

                //检查校验属性
                var validationStr = "";
                if (typeof tAttrs.required != "undefined") {
                    validationStr += " required";
                }
                if (tAttrs.minlength) {
                    validationStr += ' ng-minlength="' + tAttrs.minlength + '"';
                }
                if (tAttrs.maxlength) {
                    validationStr += ' ng-maxlength="' + tAttrs.maxlength + '"';
                }
                if (tAttrs.pattern) {
                    validationStr += ' ng-pattern="' + tAttrs.pattern + '"';
                }

                var widthStr = tAttrs.width?tAttrs.width:"172px";

                return '<input autocomplete="false" type="' + conditionType + '"  style="width:'+widthStr+';" name="' + tAttrs.conditionName + '" ng-model="' + conditionName + '" class="form-control" ' + validationStr + ' placeholder="' + conditionTip + '">';
            },
            link: function (scope, elm, attrs) {
                var optionName = attrs.conditionName;
                scope.cleanNames.push(optionName);
                scope.searchNames.push(attrs.conditionName);

                scope.formNames.push(optionName);
                scope.defaultValidation[optionName] = {};

                angular.forEach(scope.validStrs, function (validationStr, index) {
                    if (typeof attrs[validationStr] != undefined) {
                        var tip;
                        if (scope.formValidation[optionName]) {
                            tip = scope.formValidation[optionName][validationStr];
                        } else {
                            tip = gridFormTip.default[validationStr];
                            if (validationStr == "minlength") {
                                tip = tip.replace("{{minlength}}", attrs.minlength);
                            }
                            if (validationStr == "maxlength") {
                                tip = tip.replace("{{maxlength}}", attrs.maxlength);
                            }
                        }

                        scope.defaultValidation[optionName][validationStr] = tip;
                    }
                });

                //是否加上了邮箱验证
                if(attrs.emailTip == 'true'){
                    $(elm).mailAutoTip({
                        inputWidth : 172,
                        inputHeight : 33,
                        onHide:function(value){
                            scope.searchConditions[optionName] = value;
                        }
                    });
                }
            }
        };
    });

    diretiveModule.directive('gridConditionDate', function () {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridSearchBar',
            template: function (tElm, tAttrs) {
                var conditionName = "searchConditions." + tAttrs.conditionName;
                var conditionTip = tAttrs.conditionTip ? tAttrs.conditionTip : "";
                var readonly = tAttrs.readonly? tAttrs.readonly : false;

                var widthStr = tAttrs.width?tAttrs.width:"138px";

                console.log(tAttrs.conditionName);
                return '<div class="input-group input-append date">' +
                    '<input type="text" class="form-control" style="width:'+widthStr+';padding:6px 10px;" data-date-format="yyyy-mm-dd hh:ii:ss" ng-model="' + conditionName + '" placeholder="' + conditionTip + '" '+ readonly +'>' +
                    '<div class="input-group-addon add-on"><a href="javascript:;" ng-click="clearInput(' + "'" + tAttrs.conditionName + "'" + ')" class="icon-remove">X</a></div>' +
                    '</div>';
            },
            link: function (scope, elm, attrs) {
                scope.searchNames.push(attrs.conditionName);
                scope.cleanNames.push(attrs.conditionName);

                var format = attrs.dateFormat ? attrs.dateFormat : "yyyy-mm-dd hh:00:00";

                var defaultOptions = {
                    format: format,
                    todayBtn: true,
                    todayHighlight: true,
                    autoclose: true,
                    language: "zh-CN",
                    minView: "1"
                };

                if(attrs.conditionOption){
                    var cusOption = scope[attrs.conditionOption];
                    for(var key in cusOption){
                        defaultOptions[key] = cusOption[key];
                    }
                }

                $(elm).find("input").datetimepicker(defaultOptions).on("hide",function(){
                    scope.searchConditions[attrs.conditionName] = $(this).val();
                });

                scope.clearInput = function (conditionName) {
                    //$scope.searchConditions.conditionName = "";
                    delete scope.searchConditions[conditionName];
                    //清空datetimepicker输入内容
                    $(elm).find("input").val("");
                };
            }
        };
    });

    diretiveModule.directive('gridConditionSelect', function ($injector) {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridSearchBar',
            controller: function ($scope) {
                $scope.options = [];
                $scope.currentInputData = "";
            },
            template: function (tElm, tAttrs) {
                var conditionTip = tAttrs.conditionTip ? tAttrs.conditionTip : "";
                var selectValue = tAttrs.selectValue;
                var cutLength = tAttrs.cutLength;
                var strFilter = "";
                if(/^[0-9]*[1-9][0-9]*$/.test(cutLength)){
                    strFilter = "|substring:"+cutLength;
                }

                var widthStr = tAttrs.width?tAttrs.width:"172px";

                var refreshStr = "";
                if(tAttrs.refresh && tAttrs.refresh=="true"){
                    refreshStr = 'refresh="refreshFn($select.search)" refresh-delay="200"';
                }

                return '<div class="form-group" style="position: relative;">' +
                    '<ui-select ng-model="conditionConf.conditionName" theme="bootstrap" style="width:'+widthStr+';height:32px;">' +
                    '<ui-select-match placeholder="' + conditionTip + '" title="{{$select.selected.' + selectValue + '}}">{{$select.selected.' + selectValue + strFilter +'}}</ui-select-match>' +
                    '<ui-select-choices  '+refreshStr+'  repeat="option in options | filter: $select.search">' +
                    '<div ng-bind-html="option.' + selectValue + strFilter +'| highlight: $select.search" title="{{option.' + selectValue + '}}"></div>' +
                    '</ui-select-choices>' +
                    '</ui-select>' +
                    '<input type="text" class="'+(tAttrs.disabled?"show":"hide")+'" style="position: absolute;left:0;top:0;opacity:0.5;width:100%;height:100%;z-index:0;" disabled/>' +
                    '</div>';
            },
            compile: function (tElm, tAttrs) {
                return {
                    pre: function (scope, elm, attrs) {
                        if (!attrs.serviceName) {
                            console.error("gridConditionSelect的属性service-name不能为空");
                            return;
                        }
                        if (!attrs.serviceMethod) {
                            console.error("gridConditionSelect的属性service-method不能为空");
                            return;
                        }

                        var selectKey = attrs.selectKey;
                        var conditionName = attrs.conditionName;
                        var conditionTip = attrs.conditionTip ? tAttrs.conditionTip : "== 请选择 ==";

                        //初始化选择
                        scope.conditionConf = {
                            conditionName: null
                        };

                        scope.requestSelectData = $injector.get(attrs.serviceName)[attrs.serviceMethod];
                        scope.loadSelectionData = function (conditionObj,needToInit,nowTimeData) {

                            //根据最新的条件获取数据
                            var condition = scope[attrs.optionCondition];

                            if(condition==null || condition == undefined){
                                if(conditionObj != null && conditionObj != undefined){
                                    condition = conditionObj;
                                }else{
                                    condition = {};
                                }
                            }

                            scope.requestSelectData(condition).then(function (options) {
                                console.log("请求下拉列表数据成功");
                                console.log(options);

                                if(scope.currentInputData && nowTimeData != scope.currentInputData){
                                    console.log("抛弃一个了，哈哈",scope.currentInputData,nowTimeData)
                                    return;
                                }

                                if(!options){
                                    options = [];
                                }

                                // 插入全部选项
                                var totalOption = {};
                                totalOption.totalFlag = true;
                                totalOption[attrs.selectValue] = conditionTip;
                                options.splice(0, 0, totalOption);

                                scope.options.length = 0;
                                for(var index in options){
                                    scope.options.push(options[index]);
                                }

                                scope.conditionConf.conditionName = scope.options[0];//默认回显第一个

                                var initialVal = scope.searchConditions[conditionName];//初始化值
                                if(true === needToInit && initialVal){
                                    if(angular.isObject(initialVal)){
                                        console.error("gridConditionSelect指令的回显值必须是回显项的select-key");
                                        return;
                                    }
                                    for(var i=0;i<scope.options.length;i++){
                                        if(scope.options[i][selectKey] == initialVal){
                                            scope.conditionConf.optionName = scope.options[i];
                                            scope.searchConditions[conditionName] = initialVal;
                                            scope.originalSearchConditions[conditionName] = scope[i];
                                            break;
                                        }
                                    }
                                    return;
                                }

                                //默认选择第几项
                                if(attrs.checkedIndex){
                                    try{
                                        var checkedIndex = parseInt(attrs.checkedIndex);

                                        //如果是"==请选择=="项，略过
                                        if(scope.options.length == 1){
                                            return;
                                        }

                                        if(checkedIndex >= scope.options.length){
                                            console.error("out of range，默认选择项下标超过了下拉的长度");
                                            return;
                                        }
                                        scope.conditionConf.conditionName = scope.options[checkedIndex];
                                    }catch(e){
                                        console.error("默认选择的项数必须为正整数");
                                    }
                                }

                            });
                        };
                    },
                    post: function (scope, elm, attrs) {
                        scope.searchNames.push(attrs.conditionName);
                        scope.refreshNames.push(attrs.conditionName);

                        var selectKey = attrs.selectKey;
                        var conditionName = attrs.conditionName;

                        if(attrs.refresh && attrs.refresh=="true"){
                            scope.refreshFn = function(searchStr){
                                if(!searchStr) return;
                                scope.currentInputData = searchStr;
                                var conObj = {};
                                conObj[attrs.conditionName] = searchStr;
                                scope.loadSelectionData(conObj,"",searchStr);
                            };
                        }else{
                            var broadcast = attrs.broadcast && attrs.broadcast == "true";
                            if (!broadcast) {
                                scope.loadSelectionData(true);
                            }
                        }

                        scope.$watch("conditionConf.conditionName", function (newVal, oldVal) {
                            if (newVal && newVal !== oldVal) {
                                if (newVal.totalFlag) {
                                    delete scope.searchConditions[conditionName];
                                    delete scope.originalSearchConditions[conditionName];
                                } else {
                                    scope.searchConditions[conditionName] = newVal[attrs.selectKey];
                                    scope.originalSearchConditions[conditionName] = newVal;
                                }

                                if (attrs.changeDo) {
                                    scope[attrs.changeDo](newVal);
                                }
                            }
                        }, true);

                        //监听广播
                        //监听列表选项更新事件
                        if (broadcast) {
                            scope.$on("reload-" + attrs.conditionName, function (event, conditionObj) {
                                scope.loadSelectionData(conditionObj);
                            });
                        }

                        if(scope.echo){
                            scope.$on("echo-"+conditionName,function(event,selectV){
                                if(angular.isObject(selectV)){
                                    console.error("指令gridConditionSelect的回显值必须是相应的select-key值");
                                    return;
                                }
                                for(var i=0;i<scope.options.length;i++){
                                    if(scope.options[i][selectKey] == selectV){
                                        scope.conditionConf.conditionName = scope.options[i];
                                        break;
                                    }
                                }
                            });
                        }

                        //清空监听
                        scope.$on("refresh-"+conditionName,function(event,msg){
                            if(!scope.options) return;

                            scope.conditionConf.conditionName = scope.options[0];
                            //默认选择第几项
                            if(attrs.checkedIndex){
                                try{
                                    var checkedIndex = parseInt(attrs.checkedIndex);

                                    //如果是"==请选择=="项，略过
                                    if(scope.options.length == 1){
                                        return;
                                    }

                                    if(checkedIndex >= scope.options.length){
                                        console.error("out of range，默认选择项下标超过了下拉的长度");
                                        return;
                                    }
                                    scope.conditionConf.conditionName = scope.options[checkedIndex];
                                }catch(e){
                                    console.error("默认选择的项数必须为正整数");
                                }
                            }
                        });
                    }
                };
            }
        };
    });

    diretiveModule.directive('gridConditionMultiSelect', function ($injector) {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridSearchBar',
            controller: function ($scope) {
                $scope.options = [];
            },
            template: function (tElm, tAttrs) {
                var selectKey = tAttrs.selectKey;
                var selectValue = tAttrs.selectValue;
                var cutLength = tAttrs.cutLength;
                var strFilter = "";
                if(/^[0-9]*[1-9][0-9]*$/.test(cutLength)){
                    strFilter = "|substring:"+cutLength;
                }

                var refreshStr = "";
                if(tAttrs.refresh && tAttrs.refresh=="true"){
                    refreshStr = 'refresh="refreshFn($select.search)" refresh-delay="0"';
                }

                /*return '<div class="form-group" style="position: relative;">' +
                 '<ui-select ng-model="conditionConf.conditionName" theme="bootstrap" style="width:'+widthStr+';height:32px;">' +
                 '<ui-select-match placeholder="' + conditionTip + '" title="{{$select.selected.' + selectValue + '}}">{{$select.selected.' + selectValue + strFilter +'}}</ui-select-match>' +
                 '<ui-select-choices  '+refreshStr+'  repeat="option in options | filter: $select.search">' +
                 '<div ng-bind-html="option.' + selectValue + strFilter +'| highlight: $select.search" title="{{option.' + selectValue + '}}"></div>' +
                 '</ui-select-choices>' +
                 '</ui-select>' +
                 '<input type="text" class="'+(tAttrs.disabled?"show":"hide")+'" style="position: absolute;left:0;top:0;opacity:0.5;width:100%;height:100%;z-index:0;" disabled/>' +
                 '</div>';*/

                return '<div class="form-group" style="position: relative;"><select multiple data-selected-text-format="count" ng-model="conditionConf.conditionName" ng-options="option.'+selectKey+' as option.'+selectValue+' for option in options"></select></div>';
            },
            compile: function (tElm, tAttrs) {
                return {
                    pre: function (scope, elm, attrs) {
                        if (!attrs.serviceName) {
                            console.error("gridConditionSelect的属性service-name不能为空");
                            return;
                        }
                        if (!attrs.serviceMethod) {
                            console.error("gridConditionSelect的属性service-method不能为空");
                            return;
                        }

                        var selectKey = attrs.selectKey;
                        var conditionName = attrs.conditionName;
                        var conditionTip = attrs.conditionTip ? tAttrs.conditionTip : "== 请选择 ==";

                        //初始化选择
                        scope.conditionConf = {
                            conditionName: null
                        };

                        scope.requestSelectData = $injector.get(attrs.serviceName)[attrs.serviceMethod];
                        scope.loadSelectionData = function (conditionObj,needToInit) {

                            //根据最新的条件获取数据
                            var condition = scope[attrs.optionCondition];

                            if(condition==null || condition == undefined){
                                if(conditionObj != null && conditionObj != undefined){
                                    condition = conditionObj;
                                }else{
                                    condition = {};
                                }
                            }

                            scope.requestSelectData(condition).then(function (options) {
                                console.log("请求下拉列表数据成功");
                                console.log(options);

                                if(!options){
                                    options = [];
                                }

                                scope.options.length = 0;
                                for(var index in options){
                                    scope.options.push(options[index]);
                                }

                                scope.conditionConf.conditionName = null;

                                var initialVal = scope.searchConditions[conditionName];//初始化值
                                if(true === needToInit && initialVal){
                                    if(angular.isObject(initialVal)){
                                        console.error("gridConditionSelect指令的回显值必须是回显项的select-key");
                                        return;
                                    }
                                    for(var i=0;i<scope.options.length;i++){
                                        if(scope.options[i][selectKey] == initialVal){
                                            scope.conditionConf.optionName = scope.options[i];
                                            scope.searchConditions[conditionName] = initialVal;
                                            scope.originalSearchConditions[conditionName] = scope[i];
                                            break;
                                        }
                                    }
                                    return;
                                }

                                //默认选择第几项
                                if(attrs.checkedIndex){
                                    try{
                                        var checkedIndex = parseInt(attrs.checkedIndex);

                                        if(checkedIndex > scope.options.length){
                                            console.error("out of range，默认选择项下标超过了下拉的长度");
                                            return;
                                        }
                                        // scope.conditionConf.conditionName = scope.options[checkedIndex-1];
                                    }catch(e){
                                        console.error("默认选择的项数必须为正整数");
                                    }
                                }
                            });
                        };
                    },
                    post: function (scope, elm, attrs) {

                        scope.searchNames.push(attrs.conditionName);
                        scope.refreshNames.push(attrs.conditionName);

                        var selectKey = attrs.selectKey;
                        var conditionName = attrs.conditionName;

                        if(attrs.refresh && attrs.refresh=="true"){
                            scope.refreshFn = function(searchStr){
                                if(!searchStr) return;

                                var conObj = {};
                                conObj[attrs.conditionName] = searchStr;
                                scope.loadSelectionData(conObj);
                            };
                        }else{
                            var broadcast = attrs.broadcast && attrs.broadcast == "true";
                            if (!broadcast) {
                                scope.loadSelectionData(null,true);
                            }
                        }

                        /*scope.$watch("conditionConf.conditionName", function (newVal, oldVal) {
                         if (newVal && newVal !== oldVal) {
                         scope.searchConditions[conditionName] = newVal[attrs.selectKey];
                         scope.originalSearchConditions[conditionName] = newVal;

                         if (attrs.changeDo) {
                         scope[attrs.changeDo](newVal);
                         }
                         }
                         }, true);*/

                        var widthStr = tAttrs.width?tAttrs.width:"172px";
                        var conditionTip = tAttrs.conditionTip ? tAttrs.conditionTip : "";
                        var selectPicker = $(elm).find('select');
                        selectPicker.selectpicker({
                            style: 'btn-default',
                            size: 5,
                            width: widthStr,
                            noneSelectedText: conditionTip,
                            countSelectedText : conditionTip + '({0}/{1})'
                        });
                        selectPicker.on('changed.bs.select', function (event, clickedIndex, newVal, oldVal) {
                            if(clickedIndex !== undefined){
                                scope.options[clickedIndex].selected = newVal;

                                var opts = angular.copy(scope.options),opt,electedKeys=[],
                                    selectedOpts = [];
                                for(var i in opts){
                                    opt = opts[i];
                                    if(opt.selected){
                                        delete opt.selected;
                                        selectedOpts.push(opt);
                                        electedKeys.push(opt[attrs.selectKey]);
                                    }
                                }

                                scope.searchConditions[conditionName] = electedKeys;
                                scope.originalSearchConditions[conditionName] = selectedOpts;

                                if (attrs.changeDo) {
                                    scope[attrs.changeDo](selectedOpts);
                                }
                            }
                        });

                        scope.$watch("options", function (newVal, oldVal) {
                            if (newVal.length > 0 && oldVal.length == 0) {
                                refreshSelectPicker();
                            }
                        }, true);

                        function refreshSelectPicker() {
                            var selectPicker = $(elm).find('select');
                            selectPicker.selectpicker('refresh');
                        }
                        function deSelectAll() {
                            $(elm).find('select').selectpicker('deselectAll');
                        }

                        //监听广播
                        //监听列表选项更新事件
                        if (broadcast) {
                            scope.$on("reload-" + attrs.conditionName, function (event, conditionObj) {
                                scope.loadSelectionData(conditionObj);
                            });
                        }

                        if(scope.echo){
                            scope.$on("echo-"+conditionName,function(event,selectV){
                                if(angular.isObject(selectV)){
                                    console.error("指令gridConditionSelect的回显值必须是相应的select-key值");
                                    return;
                                }
                                for(var i=0;i<scope.options.length;i++){
                                    if(scope.options[i][selectKey] == selectV){
                                        // scope.conditionConf.conditionName = scope.options[i];
                                        //TODO:回显暂时不做
                                        break;
                                    }
                                }
                            });
                        }

                        //清空监听
                        scope.$on("refresh-"+conditionName,function(event,msg){
                            if(!scope.options) return;

                            // scope.conditionConf.conditionName = null;
                            for(var i in scope.options){
                                scope.options[i].selected = false;
                            }

                            delete scope.searchConditions[conditionName];
                            delete scope.originalSearchConditions[conditionName];

                            if (attrs.changeDo) {
                                scope[attrs.changeDo]([]);
                            }

                            deSelectAll();
                        });
                    }
                };
            }
        };
    });

    diretiveModule.directive('gridOperateBar', ['$injector', function ($injector) {
        return {
            scope: false,
            restrict: "E",
            replace: true,
            require: '^plusDataGrid',
            transclude: true,
            controller: function ($scope, $injector) {
                $scope.barSearch = function () {
                    if ($scope.searchDo) {
                        var result = $scope.searchDo($scope.searchConditions);
                        if (!result) {
                            return;
                        }
                    }

                    $scope.searchGrid();
                };
            },
            template: function (tElm, tAttrs) {
                var visible = false;
                if (tAttrs && tAttrs.barVisible == "true") {
                    visible = true;
                }

                var showClass = visible ? "show" : "hidden";

                return '<div ng-transclude class="form-group ' + showClass + '"></div>';
            },
            link: function (scope, elm, attrs) {
                if (attrs.serviceName && attrs.serviceMethod) {
                    $injector.get(attrs.serviceName)[attrs.serviceMethod](scope.lastSearchConditions).then();
                }
                if (attrs.searchDo) {
                    scope.searchDo = scope[attrs.searchDo];
                }
            }
        };
    }]);

    diretiveModule.directive('operateTip', ['$injector', function ($injector) {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridOperateBar',
            transclude: true,
            controller: function ($scope) {
            },
            template: function (tElm, tAttrs) {
                var finalHtml = "";
                if (tAttrs.tipTemplate) {
                    finalHtml = tAttrs.tipTemplate;
                } else {
                    finalHtml = "<span>已选择：条目总数{{pagingOptions.totalResults}}</span>";
                }

                return finalHtml;
            }
        };
    }]);

    diretiveModule.directive('operateButton', ['$injector', function ($injector) {
        return {
            scope: true,
            restrict: "E",
            replace: true,
            require: '^gridOperateBar',
            transclude: true,
            controller: function ($scope, $injector) {
                $scope.barSearch = function () {
                    if ($scope.searchDo) {
                        var result = $scope.searchDo($scope.searchConditions);
                        if (!result) {
                            return;
                        }
                    }

                    $scope.searchGrid();
                };
            },
            template: function (tElm, tAttrs) {
                var buttonLabel = "确认操作";
                if (tAttrs.buttonLabel) {
                    buttonLabel = tAttrs.buttonLabel;
                }
                return '<button type="submit" ng-disabled="!operateAllowed" class="btn btn-primary" style="margin-left:8px;float:right" ng-click="operateDo()">' + buttonLabel + '</button>';
            },
            link: function (scope, elm, attrs) {
                if (attrs.operateDo) {
                    scope.operateDo = function () {
                        scope[attrs.operateDo](scope.lastSearchConditions, scope.otherInfo, scope.pagingOptions);
                    };
                } else {
                    scope.operateDo = function () {
                        alert("未指定operate-do");
                    };
                }
            }
        };
    }]);

    diretiveModule.directive('gridDataTable', function () {
        return {
            scope: false,
            restrict: "E",
            replace: true,
            require: '^plusDataGrid',
            controller: function ($scope) {
                $scope.gridOptions = {
                    data: 'pagingOptions.myData',
                    //jqueryUITheme: true,
                    //showGroupPanel: true,
                    columnDefs: $scope.columnDefs,
                    //rowTemplate:'<tr class="even"> <td ng-repeat="col in renderedColumns"><span ng-cell></span></td> </tr>'

                    aggregateTemplate: '<div><span>{{row.label}} ({{row.totalChildren()}} {{AggItemsLabel}})</span><div></div></div>',
                    //headerRowTemplate:'<div ng-style="{ height: col.headerRowHeight }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngHeaderCell" ng-header-cell></div>',
                    headerRowTemplate: '<thead><tr><th ng-repeat="col in renderedColumns">{{col.displayName}}</th></thead>',
                    //rowTemplate: '<div ng-dblclick="onDblClickRow(row)" ng-style="{ \’cursor\’: row.cursor }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngCell {{col.cellClass}}"><div class="ngVerticalBar" ng-style="{height: rowHeight}" ng-class="{ ngVerticalBarVisible: !$last }">&nbsp;</div><div ng-cell></div></div>'
                    rowTemplate: '<tr><td  ng-repeat="col in renderedColumns" ng-cell></td></tr>',
                    //分页配置
                    enablePaging: true,
                    showFooter: true,
                    totalServerItems: 'pagingOptions.totalResults',
                    pagingOptions: $scope.pagingOptions
                };

                //检查分页参数是否发生变化
                $scope.$watch('pagingOptions.pageSize', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        $scope.searchConditions.pageSize = newVal;
                        $scope.searchGrid();
                    }
                }, true);
                $scope.$watch('pagingOptions.currentPage', function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        $scope.searchConditions.page = newVal;
                        $scope.searchGrid();
                    }
                }, true);

                //第一次搜索
                if ($scope.searchOnLoad) {
                    $scope.searchGrid();
                }
            },
            templateUrl: rootPath + '/common/js/html/gridDataTable.html'
        };
    });

    diretiveModule.directive('gridSimpleTable', function () {
        return {
            scope: false,
            restrict: "E",
            replace: true,
            require: '^plusDataGrid',
            controller: function ($scope) {

                $scope.gridOptions = {};

                //检查分页参数是否发生变化
                $scope.$watch('pagingOptions.currentPage', function (newVal, oldVal) {
                    if (newVal != oldVal) {
                        $scope.searchConditions.page = newVal;
                        $scope.searchGrid();
                    }
                }, true);

                //第一次搜索
                if ($scope.searchOnLoad) {
                    $scope.searchGrid();
                }

                $scope.changeCurrentPage = function (currentPage) {
                    if ($scope.isSearching) {
                        return;
                    }

                    $scope.pagingOptions.currentPage = currentPage;
                };
            },
            templateUrl: rootPath + '/common/js/html/gridSimpleTable.html',
            compile: function (tElm, tAttrs) {
                if(!tAttrs.columndef){
                    console.error("gridSimpleTable指令必须指定属性columnDef");
                    return;
                }

                return {
                    pre: function (scope, elm, attrs) {
                        //这是个坑，属性为columnDef,含有大写字母时候，一律转为小写
                        scope.gridOptions.columnDefs = scope[attrs.columndef];
                        //奇偶不同颜色 斑马显示
                        scope.isStriped=tAttrs.striped=='true'?true:false;
                        //是否显示分页选项
                        scope.showPagination = true;
                        if(attrs.pagination == 'false'){
                            scope.showPagination = false;
                        }
                    }
                };
            }
        };
    });

    diretiveModule.directive('gridCell', function ($compile) {
        return {
            scope: false,
            restrict: "E",
            replace: true,
            compile: function (tElm, tAttrs) {
                return {
                    pre: function (scope, elm, attrs) {
                        var html = scope.col.cellTemplate;

                        if (!html) {
                            html = "entity." + scope.col.field;

                            if (scope.col.cellFilter) {
                                html += "|" + scope.col.cellFilter
                            }

                            html = "<span>{{" + html + "}}</span>";
                        } else {
                            if (typeof html == "function") {
                                html = html(scope.entity, scope.col);
                            }
                        }

                        if(scope.selectable && scope.col.selectable === true){
                            html = "<input type='checkbox' ng-model='selectedIndexes[rowIndex]' />" + html;
                        }

                        var cellElement = $(html);
                        elm.append(cellElement);
                        $compile(cellElement)(scope);
                    }
                };
            }
        };
    });
});